package com.dzt.androidframework.database.tasks;

import com.dzt.androidframework.database.dao.TaskDao;
import com.dzt.androidframework.database.javabean.Task;
import com.dzt.androidframework.utils.JLogKit;

import java.util.List;

/**
 * Created by M02323 on 2017/6/10.
 */

public class TasksLocalDataSource implements TasksDataSource {

	private TaskDao taskDao;

	private TasksLocalDataSource() {
	}

	private static class SingletonHolder {
		static TasksLocalDataSource sInstance = new TasksLocalDataSource();
	}

	public static TasksLocalDataSource getInstance() {
		return TasksLocalDataSource.SingletonHolder.sInstance;
	}

	public void init() {
		taskDao = TaskDao.getInstance();
	}

	@Override
	public void getTasks(LoadTasksCallback callback) {
		List<Task> tasks = taskDao.findAll();
		if (tasks == null || tasks.isEmpty()) {
			callback.onDataNotAvailable();
		} else {
			callback.onTasksLoaded(tasks);
		}
	}

	@Override
	public void getTask(String taskId, GetTaskCallback callback) {
		Task task = taskDao.findById(taskId);
		if (task == null) {
			callback.onDataNotAvailable();
		} else {
			callback.onTaskLoaded(task);
		}
	}

	@Override
	public void saveTask(Task task) {
		taskDao.saveTask(task);
	}

	@Override
	public void completeTask(Task task) {
		int result = taskDao.updateTaskStatus(task, true);
		JLogKit.getInstance().i("completeTask result = " + result);
	}

	@Override
	public void completeTask(String taskId) {
		Task task = taskDao.findById(taskId);
		taskDao.updateTaskStatus(task, true);
	}

	@Override
	public void activateTask(Task task) {
		taskDao.updateTaskStatus(task, false);
	}

	@Override
	public void activateTask(String taskId) {
		Task task = taskDao.findById(taskId);
		taskDao.updateTaskStatus(task, false);
	}

	@Override
	public void updateTask(Task task) {
		taskDao.updateTask(task);
	}

	@Override
	public void clearCompletedTasks() {
		taskDao.clearCompletedTasks();
	}

	@Override
	public void refreshTasks() {
		//TODO 暂时没用
	}

	@Override
	public void deleteAllTasks() {
		taskDao.deleteAll();
	}

	@Override
	public void deleteTask(String taskId) {
		taskDao.deleteTask(taskId);
	}
}
